package mo.org.cm309.shoppingcart.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import mo.org.cm309.exception.AuthenticationException;
import mo.org.cm309.shoppingcart.entity.User;
import mo.org.cm309.shoppingcart.service.LoginService;
import mo.org.cm309.shoppingcart.service.UserService;

public class LoginServlet extends HttpServlet {
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String requestURI = req.getParameter("requestURI");
		String email 	  = req.getParameter("eMail");
		String password	  = req.getParameter("password");
		
		LoginService loginService = new LoginService();
		try {
			User user = loginService.login(email, password);
			req.getSession().setAttribute("loginUser", user);
			resp.sendRedirect(requestURI);
		} catch (AuthenticationException e) {
			if (requestURI != null && requestURI.equals(""))
				req.setAttribute("requestURI", requestURI);
			req.setAttribute("errorMsg", e.getMessage());
			req.getRequestDispatcher("/login.jsp").forward(req, resp);
		}
		
	}
	
	
}
